//服务器地址
let config = require('../config/config.js')
const host = config.request_url

/**
 * 封装wx.request请求
 * @param {String} url 请求接口地址
 * @param {String} method 请求方式
 * @param {Object} data 请求参数
 * @param {Number} headerType 请求头类型
 * @param {Boolean} isLoading 是否显示loading
 */
function http(url, method, data, headerType, isLoading, timeout) {
  var header = { 'content-type': 'application/x-www-form-urlencoded' }
  var timeout = timeout ? timeout : 20000
  if (typeof headerType === 'boolean') {
    var isLoading = headerType
    var headerType = null
  }
  if (typeof data !== 'object') {
    var isLoading = headerType
    var headerType = data
    var data = {}
  }
  if (headerType === 0) {
    header = { 'content-type': 'application/json' }
  }
  if (headerType === 1) {
    header = { 'content-type': 'application/x-www-form-urlencoded' }
  }
  if (method === 'GET') {
    header = {}
  }
  if (wx.getStorageSync('lmtc_admin_token')) {
    header['token'] = wx.getStorageSync('lmtc_admin_token')
    // header['token'] = 'eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJlZTlhYTRkYi1lMGQ4LTRiOWMtOTAzNS1kNWNjYzM2Mzc2MGQiLCJpYXQiOjE2MjQyMzg5MzEsImlzcyI6Inptem5jcyIsInN1YiI6IntcIm1hbmFnZXJJZFwiOjE0MDY3ODEwMTY4MTg2NTUyMzQsXCJuaWNrbmFtZVwiOlwi5YiY5pyI5Y2OXCIsXCJvcGVuaWRcIjpudWxsLFwidW5pb25pZFwiOm51bGx9IiwiZXhwIjoxNjI1Mjc4MTYwfQ.MPSibe1DtiF1aLAS4AmvcmnmK3JPz8xLMKlyTBkMzLo'
  }
  if (isLoading !== false) {
    wx.showLoading({ title: '加载中...' })
  }
  return new Promise((resolve, reject) => {
    let requestTask = wx.request({
      method: method,
      url: host + url,
      data: data,
      header: header,
      timeout: timeout,
      success: (res) => {
        if (res.data.code == 401) {
          wx.reLaunch({
            url: '/pages/login/login',
          })
          wx.removeStorageSync('lmtc_admin_token')
          wx.removeStorageSync('lmtc_admin_parkInfo')
        }
        if (isLoading !== false) {
          wx.hideLoading()
        }
        if (res.data.code && res.data.code != 200) {
          wx.showToast({
            title: res.data.desc,
            icon: 'none',
            duration: 3000
          })
          reject(res)
          return
        }
        resolve(res)
      },
      fail: (err) => {
        if (isLoading !== false) {
          wx.hideLoading()
        }
        if (err.errMsg == "request:fail timeout") {
          wx.showToast({
            title: '您的网络不给力，请稍后重试',
            icon: 'none',
            duration: 3000
          })
        }
        reject(err)
      }
    })
  })
}

// 导出http方法
module.exports = {
  http
}